﻿using System;
using System.ServiceProcess;
using System.Threading;
using System.Threading.Tasks;
using FutianCloudAPIService.Domains;
using FutianCloudAPIService.Nancy;
using FutianCloudAPIService.Utils;
using glTech.Log4netWrapper;
using Nancy.Hosting.Self;

namespace FutianCloudAPIService
{
    public partial class FutianCloudAPIService : ServiceBase
    {
        private CancellationTokenSource _cancelationTokenSource;

        public FutianCloudAPIService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                StartNancyHost(SystemDomain.NancyPort);

                StartHeartbeat();
            }
            catch (Exception ex)
            {
                Logger.LogError4Exception(ex);
            }
        }

        private void StartHeartbeat()
        {
            _cancelationTokenSource = new CancellationTokenSource();
            var task = Repeat.Interval(TimeSpan.FromSeconds(10), () => Heartbeat(), _cancelationTokenSource.Token);
        }

        private void Heartbeat()
        {
            Logger.LogDebug("heart beat");
        }

        /// <summary>
        /// 启动Nancy服务
        /// </summary>
        private void StartNancyHost( int portNO = 8081)
        {
            try
            {
                var hostConfiguration = new HostConfiguration
                {
                    UrlReservations = new UrlReservations() { CreateAutomatically = true }
                };
                string url = string.Format("http://localhost:{0}", portNO);

                var nancyHost = new NancyHost(new CloudBootstrapper(), hostConfiguration, new Uri(url));
                nancyHost.Start();

                System.Console.WriteLine("地址" + url);

                Logger.LogInfo("nancy start at "+ url  );
            }
            catch (Exception ex)
            {
                Logger.LogError("启动NancyHost失败.");
                Logger.LogError4Exception(ex);
            }
        }

       
        protected override void OnStop()
        {
            _cancelationTokenSource.Cancel();

            Logger.LogInfo("Service stop " );
        }

        /// <summary>
        /// 调试使用
        /// </summary>
        internal void Start()
        {
            OnStart(null);
        }
    }

  
}
